#include "stdafx.h"

#include "EngineTests.h"


// converts position from old engine to coordinates
void ConvertPosition(DWORD dwPos, int &row, int &col)
{
	int rowIndex[8] = { 5, 10, 14, 19, 23, 28, 32, 37 };
	int tempIndex = (int)dwPos - 4;
	for(int i = 0; i < 8; i++)
	{
		if(tempIndex < rowIndex[i])
		{
			row = i;
			col = dwPos - rowIndex[i];
			if(i % 2 == 0)
				col = col * 2;
			else
				col = col * 2 + 1;
			return;
		} // if
	} // for
}


// checks the position in the move
bool CheckPosition(DWORD dwPos, uint32 bitPos)
{
	// convert position
	int row, col;
	ConvertPosition(dwPos, row, col);

	// convert to bitboard
	int colIndex = 0;
	if(row % 2 == 0)
		colIndex = col / 2;
	else
		colIndex = (col - 1) / 2;

	// check bitboard
	int shift = row * 4 + colIndex;
	return (bitPos & ( 1 << shift )) == 0;
}


// checks figure at given place
bool CheckFigure(DWORD dwPos, DWORD dwFigure, BitBoard bb)
{
	if(dwFigure == WHITE_MAN)
		return CheckPosition(dwPos, bb.wm);
	else if(dwFigure == BLACK_MAN)
		return CheckPosition(dwPos, bb.bm);
	else if(dwFigure == WHITE_King)
		return CheckPosition(dwPos, bb.wk);
	else if(dwFigure == BLACK_King)
		return CheckPosition(dwPos, bb.bk);
	else
		return false;

}

bool CheckJumpCount(DWORD dwFigure, BitBoard bb, int count)
{
	uint32 jmp = 0;
	if(dwFigure == WHITE_MAN || dwFigure == WHITE_King)
		jmp = bb.bm | bb.bk;
	else
		jmp = bb.wm | bb.wk;

	return BitCount(jmp) == count;	
}

// check the move
bool CheckMove(TGameBoard board, TSingleMove* pMove, BitBoard bb, bool bJump)
{
	// check first field
	DWORD dwFirst = pMove->MovePositions[0];
	// check last field
	DWORD dwLast = pMove->MovePositions[pMove->numMoves];

	// specialni skok damy, kdy skonci na stejne pozici
	if(dwFirst == dwLast)
	{
		DWORD dwFigure = board[dwFirst];
		if(dwFigure == WHITE_King)
			return bb.wk == 0;
		else
			return bb.bk == 0;
	}


	if(CheckFigure(dwFirst, board[dwFirst], bb) == false)
		return false;



	if(pMove->Crowned)
	{
		DWORD dwQueen = board[dwFirst] == WHITE_MAN ? WHITE_King : BLACK_King;
		if(CheckFigure(dwLast, dwQueen, bb) == false)
			return false;
	}
	else
	{
		if(CheckFigure(dwLast, board[dwFirst], bb) == false)
			return false;
	}

	if(bJump == true)
	{
		// check jump figures
		for(int i = 0; i < pMove->numMoves; i++)
		{
			if(CheckFigure(pMove->RemovePositions[i], pMove->RemovedFigures[i], bb) == false)
				return false;
		}

		if(CheckJumpCount(board[dwFirst], bb, pMove->numMoves) == false)
			return false;
	}

	return true;
}